from xbmcswift2 import Plugin, xbmc, xbmcgui, xbmcaddon
from resources.lib import ondemandkorea
import re

plugin = "OnDemandKorea Video"
__url__ = 'https://code.google.com/p/korean-drama-tv/'
__date__ = '05-05-2014'
__version__ = '0.0.1'
settings = xbmcaddon.Addon(id='plugin.video.ondemandkorea.com')
cookiepath = xbmc.translatePath('special://temp/')

plugin = Plugin()
odk = ondemandkorea.ODK()

def strip_html(text):
  def fixup(m):
    text = m.group(0)
    if text[:1] == "<":
      return "" # ignore tags
    if text[:2] == "&#":
      try:
        if text[:3] == "&#x":
          return unichr(int(text[3:-1], 16))
        else:
          return unichr(int(text[2:-1]))
      except ValueError:
        pass
    elif text[:1] == "&":
      import htmlentitydefs
      entity = htmlentitydefs.entitydefs.get(text[1:-1])
      if entity:
        if entity[:2] == "&#":
          try:
            return unichr(int(entity[2:-1]))
          except ValueError:
            pass
        else:
          return unicode(entity, "iso-8859-1")
    return text # leave as is
  return re.sub("(?s)<[^>]*>|&#?\w+;", fixup, text)
  
def checkLoginInfo():
  if settings.getSetting('username') == '' or settings.getSetting('password') == '':
    settings.openSettings()
    return True
  return True
                                           
def addItems(items):
  result = []
  for item in items:
    title = item['title']
    playable = item.get('playable', False)
    result.append({
      'label':strip_html(item['title']),
      'path':plugin.url_for(item['mode'], url=item['url']),
      'is_playable':playable,
      'thumbnail':item.get('thumb', '')})            
  return result;

@plugin.route('/')
def index():
  menu = odk.parseMenu()  
  return addItems(menu)

@plugin.route('/media/<url>')
def browse(url):
  menu = odk.parseNewMedia(url)  
  return addItems(menu)

@plugin.route('/video/<url>')
def play(url):
  info = odk.parseVideo(url)
  vurl = "{0:s} playpath={1:s}".format(info['base'], info['video'])  
  plugin.set_resolved_url(vurl)   

if __name__ == '__main__':
  if checkLoginInfo():
    odk.login(settings.getSetting('username'), settings.getSetting('password'), cookiepath)
    plugin.run()
